package cn.lg.soar.core.util.easyexcel.converters;

import cn.lg.soar.common.util.data.DataUtil;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

/**
 * easyexcel 布尔值转换器
 * @author luguoxiang
 * @date 2021-08-16
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class BooleanConverter implements Converter<Boolean> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return Boolean.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Boolean convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        String stringValue = cellData.getStringValue();
        if ("是".equals(stringValue) || "yes".equalsIgnoreCase(stringValue) || "true".equalsIgnoreCase(stringValue) || "1".equals(stringValue)) {
            return Boolean.TRUE;
        }
        if ("否".equals(stringValue) || "no".equalsIgnoreCase(stringValue) || "false".equalsIgnoreCase(stringValue) || "0".equals(stringValue)) {
            return Boolean.FALSE;
        }
        if (DataUtil.isEmpty(stringValue)) {
            return null;
        }
        throw new RuntimeException("无法转换“" + stringValue + "”为 Boolean 类型");
    }

    @Override
    public WriteCellData<?> convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        if (value == null) {
            return new WriteCellData<>("");
        }
        return new WriteCellData<>(value ? "是" : "否");
    }

}
